package com.haocang.szgm.ui.waterpoint.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.esri.core.geometry.Point;
import com.haocang.commonlib.gismap.GisMapConfig;
import com.haocang.szgm.R;
import com.haocang.szgm.activity.comm.CommMapFinalActivity;
import com.haocang.szgm.activity.tool.CacheActivityUtil;
import com.haocang.szgm.requestcenter.DataModel;
import com.haocang.commonlib.network.request.UploadUtil;
import com.haocang.commonlib.network.interfaces.InitDataOneBeanBack;
import com.haocang.szgm.ui.tools.activity.EnclosureListActivity;
import com.haocang.szgm.ui.tools.activity.MultiSelectDialog;
import com.haocang.szgm.ui.tools.enums.MultiSelectEnum;
import com.haocang.szgm.ui.waterpoint.bean.WaterPointBean;
import com.haocang.szgm.utils.config.Config;
import com.haocang.szgm.utils.config.WebApi;
import com.haocang.commonlib.loadingdialog.LoadingDialog;
import com.haocang.szgm.utils.tools.CacheData;
import com.haocang.szgm.utils.tools.CustomDialog;
import com.haocang.szgm.utils.tools.MyTextUtils;

import net.tsz.afinal.annotation.view.ViewInject;

import org.json.JSONException;
import org.json.JSONObject;

public class SureWaterPointActivity extends CommMapFinalActivity {


    private Context context;
    private LoadingDialog dialog;
    private WaterPointBean model;

    @ViewInject(id = R.id.tv_SeepeNo)
    EditText tv_SeepeNo;
    @ViewInject(id = R.id.tv_Location)
    EditText tv_Location;
    @ViewInject(id = R.id.tv_Measures)
    TextView tv_Measures;

    @ViewInject(id = R.id.ck_1)
    CheckBox ck_1;
    @ViewInject(id = R.id.ck_2)
    CheckBox ck_2;
    @ViewInject(id = R.id.ck_3)
    CheckBox ck_3;
    @ViewInject(id = R.id.ck_4)
    CheckBox ck_4;

    @ViewInject(id = R.id.submit_js)
    Button submit_js;
    @ViewInject(id = R.id.submit_no_js)
    Button submit_no_js;
    @ViewInject(id = R.id.submit_yuchuli)
    Button submit_yuchuli;

    private RequestQueue mQueue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        CacheActivityUtil.addActivity(SureWaterPointActivity.this);

        initView();

        initEvent();

        initData();

        initMyLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CacheActivityUtil.finishSingleActivity(SureWaterPointActivity.this);
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_sure_water_point;
    }

    @Override
    protected boolean showNavigation() {
        return true;
    }

    @Override
    protected int showMoreIcon() {
        return  R.drawable.icon_fujian_01;
    }

    @Override
    protected boolean showMedia() {
        return true;
    }

    @Override
    protected boolean showMapPipe() {
        return false;
    }

    @Override
    protected String showTitleName() {
        return "积水点确认";
    }

    private void initView() {

        mQueue = Volley.newRequestQueue(this);

        SetFileStatus("0");
    }


    private void initEvent() {

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }
        });


        iv_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, EnclosureListActivity.class);
                intent.putExtra("BILLID", model.getID());
                startActivity(intent);
            }
        });


        submit_js.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StartSubmit();
            }
        });
        submit_no_js.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CancelSubmit();
            }
        });
        submit_yuchuli.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


			   if(tv_Measures.getText().toString().equals("")){
                    ToastShow("请输入预处置措施！");
                    return;
                }
			
                CustomDialog.Builder builder = new CustomDialog.Builder(context);
                builder.setTitle("提示");
                builder.setMessage("您确定对该积水点进行预处理?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //设置你的操作事项
                        MeasuresSubmit();
                    }
                });

                builder.setNegativeButton("取消",
                        new android.content.DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
            }
        });


        tv_Measures.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(context, MultiSelectDialog.class);
                it.putExtra("ID", "");
                it.putExtra("DECIDE", "Name");
                it.putExtra("TYPE", MultiSelectEnum.Measures);
                it.putExtra("SELECTED", tv_Measures.getText().toString());
                it.putExtra("IsAlone", false);
                it.putExtra("ManuaInput", true);
                startActivityForResult(it, 104);
            }
        });


        ck_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SetFileStatus("3");
            }
        });
        ck_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SetFileStatus("0");
            }
        });
        ck_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SetFileStatus("1");
            }
        });
        ck_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SetFileStatus("2");
            }
        });

    }

    private void initData() {

        Intent it = getIntent();
        String ID = it.getStringExtra("ID");
        dialog = new LoadingDialog(context, "加载中");
        dialog.show();
        String ApiUrl = Config.host + WebApi.Api_WaterPointDetail + ID;
        DataModel.GetApiRequestOneMode("WaterPointBean", ApiUrl, new InitDataOneBeanBack<WaterPointBean>() {

            @Override
            public void callbak(boolean b, WaterPointBean data, String msg) {
                if (b) {
                    model = data;


                    if(model.getIsHandle() == 1){
                        submit_yuchuli.setVisibility(View.GONE);
                    }

                    Point waterPoint = new Point(model.getX(), model.getY());
                    if (model.getX() != 0 && model.getY() != 0) {

                        int icon = R.mipmap.jsd_yyd;
                        if(model.getIsDelete().equals("N")){
                            if(MyTextUtils.IsString(model.getType()).equals("1")){
                                icon = R.mipmap.jsd_yyd;
                            }else if(MyTextUtils.IsString(model.getType()).equals("2")){
                                icon = R.mipmap.jsd_jsd;
                            }
                        }else if(model.getIsDelete().equals("Y")){
                            icon = R.mipmap.jsd_gray;
                        }else{
                            if (model.getStatus().equals("0")) {
                                icon = R.mipmap.jsd_r;
                            } else if (model.getStatus().equals("1")) {
                                icon = R.mipmap.jsd_y;
                            } else if (model.getStatus().equals("2")) {
                                icon = R.mipmap.jsd_green;
                            }
                        }

                        addpoint(waterPoint,icon);
                    }
                    mMapView.centerAt(waterPoint, true);
                    mMapView.setResolution(GisMapConfig.resolution[GisMapConfig.MAP_DEFAULT_RES]);// 设置当前显示的分辨率

                    tv_SeepeNo.setText(model.getSeepeNo());
                    tv_Location.setText(model.getLocation());
                    tv_Measures.setText(model.getMeasures());
                } else {
                    ToastShow("数据加载出错：" + msg);
                }
                dialog.close();

            }
        });

    }

    /**
     * ===============================================
     * 创建时间：2019/3/27 20:15
     * 编 写 人：ShenC
     * 方法说明：确定积水
     * ================================================
     * 修改内容：      修改时间：      修改人：
     * ===============================================
     *///确定积水
    private void StartSubmit() {
        try {
            String FileStatus = GetFileStatus();// MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetFileStatusList(), 0, tv_FileStatus.getText().toString());

            JSONObject maps = new JSONObject();
            maps.put("ID", model.getID());
            maps.put("StartWaterDate", MyTextUtils.getNowDatatoString());
            maps.put("ArrivalDT", MyTextUtils.getNowDatatoString());
            maps.put("Status", "0");
            maps.put("IsDelete", "S");
            maps.put("Msg", CacheData.UserName()+":确定发生积水");
            maps.put("OperationType", "Start");
            selectFileStatus(maps, "请完善积水信息！", "确定积水失败！", false, FileStatus);

        } catch (JSONException e) {
            ToastShow("保存失败," + e.toString());
            e.printStackTrace();
        }

    }

    /**
     * ===============================================
     * 创建时间：2019/3/27 20:16
     * 编 写 人：ShenC
     * 方法说明：取消积水
     * ================================================
     * 修改内容：      修改时间：      修改人：
     * ===============================================
     *///取消积水
    private void CancelSubmit() {

        try {
            String FileStatus = GetFileStatus();// MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetFileStatusList(), 0, tv_FileStatus.getText().toString());

            JSONObject maps = new JSONObject();
            maps.put("ID", model.getID());
            maps.put("ArrivalDT", MyTextUtils.getNowDatatoString());
            maps.put("IsDelete", "Y");
            maps.put("Msg", CacheData.UserName()+":确定未积水");
            maps.put("OperationType", "Cancel");
            selectFileStatus(maps, "处理成功！", "确定未积水失败！", true, FileStatus);

        } catch (JSONException e) {
            ToastShow("保存失败," + e.toString());
            e.printStackTrace();
        }

    }


    private void MeasuresSubmit() {

        try {
            String ls_Measures = tv_Measures.getText().toString().trim();
            if (MyTextUtils.IsNullByString(ls_Measures)) {
                ls_Measures = "";
            }
            String FileStatus = GetFileStatus();
            JSONObject maps = new JSONObject();
            maps.put("ID", model.getID());
            maps.put("IsHandle", 1);
            maps.put("Measures", ls_Measures);
            maps.put("Status", 0);
            maps.put("Msg", CacheData.UserName()+":预处理了积水点");
            maps.put("OperationType", "Measures");
            selectFileStatus(maps, "预处理成功！", "预处理失败！", true, FileStatus);

        } catch (JSONException e) {
            ToastShow("保存失败," + e.toString());
            e.printStackTrace();
        }

    }

    private void selectFileStatus(final JSONObject maps, final String SuccessLog, final String ErrorLog, final boolean isExit, String FileStatus) {

        if (GetFilelist().size() > 0) {
            if (FileStatus.equals("")) {
                ToastShow("请选择附件状态！");
                return;
            } else {
                UploadBill(maps, SuccessLog, ErrorLog, isExit, FileStatus);
            }
        } else {
            UploadBill(maps, SuccessLog, ErrorLog, isExit, FileStatus);
        }
    }

    /**
     * ===============================================
     * 创建时间：2019/3/29 11:28
     * 编 写 人：ShenC
     * 方法说明：保存工单和附件的提交方法
     * ================================================
     * 修改内容：      修改时间：      修改人：
     * ===============================================
     *///保存工单和附件的提交方法
    private void UploadBill(JSONObject maps, final String SuccessLog, final String ErrorLog, final boolean isExit, final String FileStatus) {
        try {
            JSONObject param = new JSONObject();
            param.put("info", maps);
            param.put("filename", "WaterPoint");
            param.put("CreateUserId", CacheData.UserID());
            param.put("CreateUserName", CacheData.UserName());
            param.put("FileStatus", FileStatus);

            dialog = new LoadingDialog(context, "保存中");
            dialog.show();
            UploadUtil request = new UploadUtil(
                    Config.host + WebApi.Api_ParamFileUpload,
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            dialog.close();
                            ToastShow(ErrorLog + ",请求超时！");
                            error.printStackTrace();
                        }
                    }, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject josnobject = new JSONObject(response);
                        if (josnobject.getBoolean("Result")) {

                            dialog.close();
                            ToastShow(SuccessLog);
                            if(!isExit){
                                CacheData.WaterPoint_UPDATE = true;
                                CacheData.mWaterPointID = model.getID();
                                Intent it = new Intent(context, WaterPointDetailActivity.class);
                                startActivity(it);
                            }
                            finish();
                            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                        } else {
                            dialog.close();
                            ToastShow(ErrorLog + josnobject.getString("Msg"));
                        }
                    } catch (JSONException e) {

                        dialog.close();
                        ToastShow(ErrorLog + e.toString());
                        e.printStackTrace();
                    }
                }

            }, "f_file[]", GetFilelist(), param);
            request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f));
            mQueue.add(request);
        } catch (JSONException e) {
            dialog.close();
            ToastShow(ErrorLog + e.toString());
            e.printStackTrace();
        }
    }


    //获取附件的状态
    private String GetFileStatus() {
        if (ck_1.isChecked()) {
            return "3";
        } else if (ck_2.isChecked()) {
            return "0";
        } else if (ck_3.isChecked()) {
            return "1";
        } else if (ck_4.isChecked()) {
            return "2";
        }
        return "0";
    }

    //设置附件的状态
    private void SetFileStatus(String Status) {
        switch (Status) {
            case "3":
                ck_1.setChecked(true);
                ck_2.setChecked(false);
                ck_3.setChecked(false);
                ck_4.setChecked(false);
                break;
            case "0":
                ck_1.setChecked(false);
                ck_2.setChecked(true);
                ck_3.setChecked(false);
                ck_4.setChecked(false);
                break;
            case "1":
                ck_1.setChecked(false);
                ck_2.setChecked(false);
                ck_3.setChecked(true);
                ck_4.setChecked(false);
                break;
            case "2":
                ck_1.setChecked(false);
                ck_2.setChecked(false);
                ck_3.setChecked(false);
                ck_4.setChecked(true);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 104 && resultCode == 100) {
            String w_name = data.getStringExtra("Name");
            tv_Measures.setText(w_name);
        }

    }

        //退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            return super.onKeyDown(keyCode, event);
        } else {
            return false;
        }
    }


}
